package com.ruin.tech.ahri.service.impl;

import com.ruin.tech.ahri.dao.AppreciateMapper;
import com.ruin.tech.ahri.dao.ArticleMapper;
import com.ruin.tech.ahri.model.dto.*;
import com.ruin.tech.ahri.service.IAppreciateService;
import com.ruin.tech.ahri.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @program ahri
 * @description: 点赞服务
 * @author: ruin
 * @create: 2019/12/18 15:11
 */
@Service
public class AppreciateImpl implements IAppreciateService {

    @Autowired
    AppreciateMapper appreciateMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appreciate(ArticleDTO param) throws Exception {
        Long articleId = param.getId();
        Long loginUserId = param.getLoginUserId();
        Integer isAppreciate = param.getIsAppreciate();

        Appreciate appreciate = new Appreciate();
        appreciate.setArticleId(articleId);
        appreciate.setUserId(loginUserId);
        appreciate.setIsVaild(isAppreciate);
        appreciate.setCreateTime(new Date());
        appreciate.setUpdateTime(new Date());
        appreciateMapper.insertOrUpdate(appreciate);

        ArticleExample articleExample = new ArticleExample();
        articleExample.createCriteria().andIdEqualTo(articleId);
        List<Article> articles = articleMapper.selectByExample(articleExample);
        Article article = articles.get(0);
        if(isAppreciate == 1){
            article.setLikeCount(article.getLikeCount()+1);
        }else{
            if(article.getLikeCount()>0) {
                article.setLikeCount(article.getLikeCount() - 1);
            }
        }
        articleMapper.updateByExampleSelective(article,articleExample);
    }
}
